import 'package:flutter_riverpod/flutter_riverpod.dart';

import '../models/calendar_event.dart';
import '../services/calendar_service.dart';

/// 日历事件列表状态提供者
final calendarEventsProvider = StateNotifierProvider<CalendarEventsNotifier, List<CalendarEvent>>((ref) {
  final calendarService = ref.watch(calendarServiceProvider);
  return CalendarEventsNotifier(calendarService);
});

/// 当前选中日期提供者
final selectedDateProvider = StateProvider<DateTime>((ref) {
  return DateTime.now();
});

/// 当前选中事件类型过滤器提供者
final eventTypeFilterProvider = StateProvider<CalendarEventType?>((ref) {
  return null; // null 表示显示所有类型
});

/// 日历视图类型提供者（月视图、周视图、日视图）
final calendarViewTypeProvider = StateProvider<CalendarViewType>((ref) {
  return CalendarViewType.month;
});

/// 日历视图类型枚举
enum CalendarViewType {
  /// 月视图
  month,
  /// 周视图
  week,
  /// 日视图
  day,
  /// 议程视图
  agenda,
  /// 全部视图
  all
}

/// 日历事件状态管理类
class CalendarEventsNotifier extends StateNotifier<List<CalendarEvent>> {
  final CalendarService _calendarService;
  
  CalendarEventsNotifier(this._calendarService) : super([]);

  /// 加载所有日历事件
  Future<void> loadEvents() async {
    final events = await _calendarService.getAllEvents();
    state = events;
  }

  /// 添加新事件
  Future<void> addEvent(CalendarEvent event) async {
    final createdEvent = await _calendarService.createEvent(event);
    if (createdEvent != null) {
      state = [...state, createdEvent];
    }
  }

  /// 根据ID删除事件
  Future<void> removeEvent(String id) async {
    final success = await _calendarService.deleteEvent(id);
    if (success) {
      state = state.where((event) => event.id != id).toList();
    }
  }

  /// 更新事件
  Future<void> updateEvent(CalendarEvent updatedEvent) async {
    final updated = await _calendarService.updateEvent(updatedEvent);
    if (updated != null) {
      state = state.map((event) {
        if (event.id == updated.id) {
          return updated;
        }
        return event;
      }).toList();
    }
  }

  /// 创建新事件
  Future<CalendarEvent?> createEvent({
    required String title,
    required String description,
    required DateTime startTime,
    DateTime? endTime,
    required CalendarEventType eventType,
    String? location,
    List<String>? participants,
    bool isAllDay = false,
    bool isRecurring = false,
    String? recurrenceType,
    int? reminderMinutes,
  }) async {
    final newEvent = CalendarEvent(
      id: 'new', // 临时ID，实际ID将由后端生成
      title: title,
      description: description,
      startTime: startTime,
      endTime: endTime,
      eventType: eventType,
      location: location,
      participants: participants,
      isAllDay: isAllDay,
      isRecurring: isRecurring,
      recurrenceType: recurrenceType,
      reminderMinutes: reminderMinutes,
    );
    
    final createdEvent = await _calendarService.createEvent(newEvent);
    if (createdEvent != null) {
      state = [...state, createdEvent];
    }
    return createdEvent;
  }

  /// 获取指定日期的所有事件
  List<CalendarEvent> getEventsForDay(DateTime day) {
    final normalizedDay = DateTime(day.year, day.month, day.day);
    
    return state.where((event) {
      final eventStart = DateTime(
        event.startTime.year,
        event.startTime.month,
        event.startTime.day,
      );
      
      // 处理单日事件
      if (!event.isRecurring) {
        return eventStart.isAtSameMomentAs(normalizedDay);
      }
      
      // 处理重复事件
      if (event.recurrenceType == 'daily') {
        return eventStart.isBefore(normalizedDay) || eventStart.isAtSameMomentAs(normalizedDay);
      } else if (event.recurrenceType == 'weekly') {
        return eventStart.weekday == normalizedDay.weekday && 
               (eventStart.isBefore(normalizedDay) || eventStart.isAtSameMomentAs(normalizedDay));
      } else if (event.recurrenceType == 'monthly') {
        return eventStart.day == normalizedDay.day && 
               (eventStart.isBefore(normalizedDay) || eventStart.isAtSameMomentAs(normalizedDay));
      } else if (event.recurrenceType == 'yearly') {
        return eventStart.month == normalizedDay.month && 
               eventStart.day == normalizedDay.day && 
               (eventStart.isBefore(normalizedDay) || eventStart.isAtSameMomentAs(normalizedDay));
      }
      
      return false;
    }).toList();
  }

  /// 获取指定月份的所有事件
  List<CalendarEvent> getEventsForMonth(DateTime month) {
    final normalizedMonth = DateTime(month.year, month.month, 1);
    final nextMonth = DateTime(month.year, month.month + 1, 1);
    
    return state.where((event) {
      final eventStart = event.startTime;
      
      // 非重复事件：检查是否在当月
      if (!event.isRecurring) {
        return eventStart.isAfter(normalizedMonth.subtract(const Duration(days: 1))) && 
               eventStart.isBefore(nextMonth);
      }
      
      // 重复事件：检查原始事件是否在当月之前或当月
      return eventStart.isBefore(nextMonth);
    }).toList();
  }

  /// 获取所有事件
  List<CalendarEvent> getAllEvents() {
    return List<CalendarEvent>.from(state)
      ..sort((a, b) => a.startTime.compareTo(b.startTime));
  }

  /// 按事件类型过滤事件
  List<CalendarEvent> filterByEventType(CalendarEventType type) {
    return state.where((event) => event.eventType == type).toList();
  }

  /// 加载示例数据（用于测试）
  void loadSampleEvents() {
    // 从后端加载真实数据
    loadEvents();
  }
}
